package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@Service(timeout = 200000)
public class VoiceApiImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;


    /**
     * 保存
     *
     * @param voice
     */
    @Override
    public void save(Voice voice) {
        voice.setVid(idService.getNextId("voice"));
        mongoTemplate.insert(voice);
    }

    /**
     * 根据id查询
     *
     * @param voiceId
     * @return
     */
    @Override
    public Voice findById(String voiceId) {
        return mongoTemplate.findById(new ObjectId(voiceId), Voice.class);
    }

    /**
     * 查询语音
     */
    @Override
    public Voice findByState(Long userId){
        Query query = new Query(
                Criteria.where("userId").ne(userId)
                        .and("state").is(0)
        );

        //query.with(Sort.by(Sort.Order.desc("created")));




        return mongoTemplate.findOne(query,Voice.class);
    }

    /**
     * 将voice的state设置为1
     * @param voice
     */
    @Override
    public void setVoiceState(Voice voice) {
        Query query = new Query(
                Criteria.where("vid").is(voice.getVid())
        );

        Update update = new Update();
        update.set("state",voice.getState());
        mongoTemplate.updateFirst(query,update,Voice.class);
    }




}
